package org.example.controller;

import org.example.dao.ItemNotExistException;
import org.example.dao.UserRepository;
import org.example.controller.pojo.JsonSuccessResponse;
import org.example.controller.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.*;
import java.util.Date;

@Controller
@RequestMapping("/quickstart")
public class QuickStartController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/handle01")
    public ModelAndView handle01() {
        Integer t = 10 / 0; // Add this line to trigger ArithmeticException

        Date date = new Date();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("date", date);
        modelAndView.setViewName("success");
        return modelAndView;
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public @ResponseBody User showUser(@PathVariable("id") Integer id, HttpServletRequest Request) {
        System.out.println("The id to show " + id);
        User tUser = userRepository.getById(id);
        if (tUser == null) {
            throw new ItemNotExistException("找不到用户");
        }
        return tUser;
    }

    @RequestMapping(value = "/set_cookie/{key}", method = RequestMethod.GET)
    public @ResponseBody JsonSuccessResponse SetCookie(@PathVariable("key") String key, HttpServletResponse response, HttpServletRequest request) {
        Cookie cookie = new Cookie(key, "The value for " + key);
        cookie.setMaxAge(1 * 60);
        cookie.setPath("/");
        response.addCookie(cookie);

        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        System.out.println("Loged in user: " + username);

        return new JsonSuccessResponse("Hey success");
    }

    @RequestMapping(value = "/get_cookies", method = RequestMethod.GET)
    public @ResponseBody JsonSuccessResponse getCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();

        if (null == cookies) {
            throw new ItemNotExistException("There isn't any cookie!");
        }
        return new JsonSuccessResponse(cookies);
    }

}
